package cn.iocoder.yudao.module.ai.controller.admin.busimodel;

import ch.qos.logback.core.encoder.Encoder;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.ai.dal.dataobject.jupyter.JupyterDO;
import cn.iocoder.yudao.module.ai.service.jupyter.JupyterService;
import cn.iocoder.yudao.module.ai.utils.AssertUtil;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.ai.controller.admin.busimodel.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.busimodel.BusiModelDO;
import cn.iocoder.yudao.module.ai.service.busimodel.BusiModelService;

@Tag(name = "管理后台 - 业务模型")
@RestController
@RequestMapping("/ai/busiModel")
@Validated
public class BusiModelController {

    @Resource
    private BusiModelService busiModelService;
    @Resource
    private JupyterService jupyterService;
    @Resource
    private DeptApi deptApi;

    @PostMapping("/saveModelAndParams")
    @Operation(summary = "保存业务模型以及模型参数")
    @PreAuthorize("@ss.hasPermission('ai:busi-model:create')")
    public CommonResult<Integer> saveModelAndParams(@Valid @RequestBody BusiModelSaveReqVO createReqVO) {
        createReqVO.setSuplierId(deptApi.queryFirstDept(SecurityFrameworkUtils.getLoginUserDeptId()));
        return success(busiModelService.createBusiModel(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新业务模型及参数")
    @PreAuthorize("@ss.hasPermission('ai:busi-model:update')")
    public CommonResult<Boolean> updateBusiModel(@Valid @RequestBody BusiModelSaveReqVO updateReqVO) {
        busiModelService.updateBusiModel(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除业务模型及参数")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:busi-model:delete')")
    public CommonResult<Boolean> deleteBusiModel(@RequestParam("id") Integer id) {
        busiModelService.deleteBusiModel(id);
        return success(true);
    }

    @GetMapping("/getModelAndParam")
    @Operation(summary = "获取业务模型及参数")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:busi-model:query')")
    public CommonResult<BusiModelDO> getModelAndParam(@RequestParam("id") Integer id) {
        BusiModelDO busiModel = busiModelService.getBusiModel(id);
        return success(busiModel);
    }

    @GetMapping("/page")
    @Operation(summary = "获得业务模型分页清单")
    @PreAuthorize("@ss.hasPermission('ai:busi-model:query')")
    public CommonResult<PageResult<BusiModelRespVO>> getBusiModelPage(@Valid BusiModelPageReqVO pageReqVO) {
        PageResult<BusiModelDO> pageResult = busiModelService.getBusiModelPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, BusiModelRespVO.class));
    }

    @GetMapping("/download")
    @Operation(summary = "下载业务模型")
    @PreAuthorize("@ss.hasPermission('ai:busi-model:query')")
    public ResponseEntity<InputStreamResource> download(@RequestParam("id") Integer id) throws IOException {
        BusiModelDO busiModel = busiModelService.getBusiModel(id);
        JupyterDO jupyter = jupyterService.getJupyter(busiModel.getJupyterId());
        AssertUtil.isNotEmpty(busiModel,"未找到业务模型。");
        AssertUtil.isNotEmpty(jupyter,"未找到jupyter工作区。");
        String filePath = busiModelService.buildBusinessModel(busiModel, jupyter);
        try {
            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                return ResponseEntity.notFound().build();
            }
            // 读取文件内容
            FileInputStream inputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(inputStream);

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "busiModel.zip" + "\"");
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
            headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .body(resource);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }


}